package com.example.medicalretrieval;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.common.OSSConstants;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationToken;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.common.utils.IOUtils;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.GetObjectResult;
//import com.aliyun.auth.credentials.Credential;
//import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
//import com.aliyun.sdk.service.sts20150401.AsyncClient;
//import com.aliyun.sdk.service.sts20150401.models.AssumeRoleRequest;
//import com.aliyun.sdk.service.sts20150401.models.AssumeRoleResponse;
import com.example.medicalretrieval.dao.BrowsingHistoryDao;
import com.example.medicalretrieval.dao.DownloadHistoryDao;
import com.example.medicalretrieval.pojo.BrowsingHistory;
import com.example.medicalretrieval.pojo.DownloadHistory;
import com.github.barteksc.pdfviewer.PDFView;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

//import darabonba.core.client.ClientOverrideConfiguration;

public class ShowPdfActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView pdfDownload;
    private String uri;
    private final int MY_PERMISSIONS_REQUEST_READ_STORAGE = 1;
    private PDFView pdfView;
    private BrowsingHistoryDao browsingHistoryDao;
    private DownloadHistoryDao downloadHistoryDao;
    private String authors;
    private String title;
    private OSSClient oss;
    private GetObjectRequest get;
    private String name;
    private String filePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_pdf);
        init();
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        uri = extras.getString("PdfUri");
        title = extras.getString("title");
        name = extras.getString("name");
        filePath = extras.getString("filePath");
        authors = extras.getString("authors");

        TextView pdf_title = findViewById(R.id.pdf_title);
        pdf_title.setText(title);

        ImageView back = findViewById(R.id.pdf_back);
        back.setOnClickListener(this);

        pdfDownload = findViewById(R.id.pdf_download);
        pdfDownload.setOnClickListener(this);
        pdfView = findViewById(R.id.pdfView);

        System.out.println("demo在下一行");
        demo();



        browsing();
    }

    /**
     * 点进来了，也就浏览了，记录一下
     */
    private void browsing(){
        browsingHistoryDao = MyApplication.getInstance().getBrowsingHistoryDataBase().browsingHistoryDao();
        browsingHistoryDao.deleteByTitle(title);
        BrowsingHistory browsingHistory = new BrowsingHistory();
        browsingHistory.setAuthors(authors);
        long time=System.currentTimeMillis();//long now = android.os.SystemClock.uptimeMillis();
//        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d1=new Date(time);
        browsingHistory.setDate(d1);
        browsingHistory.setTitle(title);
        browsingHistoryDao.insert(browsingHistory);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.pdf_back:
                finish();
                break;
            case R.id.pdf_download:
                try {
                    initPermission();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;

        }
    }

    private void initPermission() throws IOException {
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_STORAGE);
        }else{
            downFile();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case MY_PERMISSIONS_REQUEST_READ_STORAGE:{
                if(grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    //权限被授予
                    try {
                        downFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    //权限被拒绝
                    Toast.makeText(this, "未获取权限，无法下载文档", Toast.LENGTH_SHORT).show();
                }
                break;
            }
        }
    }

    /**
     * 下载文件，下载到特定的地点
     */
    private void downFile() throws IOException {
        //记录下载情况。
        downloadHistoryDao = MyApplication.getInstance().getDownloadHistoryDataBase().downloadHistoryDao();
        DownloadHistory downloadHistory = new DownloadHistory();
        downloadHistoryDao.deleteByTitle(title);
        downloadHistory.setDownloadUri(".\\app\\src\\main\\assets\\"+name);
        downloadHistory.setAuthors(authors);
        downloadHistory.setDate(new Date(System.currentTimeMillis()));
        downloadHistory.setTitle(title);
        downloadHistoryDao.insert(downloadHistory);
        File file = new File(".\\app\\src\\main\\assets\\"+name); // 此处为伪代码，实际为一个真实存在的文件，即你想复制的文件。
        copyFile(file, AUDIO_FILE_PATH);
    }
    private static final String AUDIO_FILE_PATH =
            Environment.getExternalStorageDirectory().getPath()+"/download/";


    /**
     * 根据文件路径拷贝文件
     * @param src 源文件
     * @param destPath 目标文件路径
     * @return boolean 成功true、失败false
     */
    public boolean copyFile(File src, String destPath) {
        boolean result = false;
        if ((src == null) || (destPath== null)) {
            return result;
        }
        File dest= new File(destPath + name);
        if (dest!= null && dest.exists()) {
            dest.delete(); // delete file
        }
        try {
            dest.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        FileChannel srcChannel = null;
        FileChannel dstChannel = null;

        try {
            srcChannel = new FileInputStream(src).getChannel();
            dstChannel = new FileOutputStream(dest).getChannel();
            srcChannel.transferTo(0, srcChannel.size(), dstChannel);
            result = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return result;
        }
        try {
            srcChannel.close();
            dstChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    private void init(){
        filePath = "FOCUS超声刀开放性甲状腺切除术的临床疗效评价_薛家鹏1679127663116.pdf";
        name = "FOCUS超声刀开放性甲状腺切除术的临床疗效评价_薛家鹏.pdf";

        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
        String accessKeyId = "LTAI5tNxkvsUUy75G4BiW9sQ";
        String accessKeySecret = "t8o4NWKiYoIbEsS7KU4Dsfid12R8Im";
        // 从STS服务获取的安全令牌（SecurityToken）。
        String securityToken = "acs:ram::1678873764269912:role/aliyunosstokengeneratorrole";
        String bucketName = "medical-retrieval";
        // 创建OSSClient实例。
        oss = null;


        OSSCredentialProvider credetialProvider = new OSSFederationCredentialProvider() {
            @Override
            public OSSFederationToken getFederationToken() {
                try {
                    URL stsUrl = new URL("http://localhost:8080/distribute-token.json");
                    HttpURLConnection conn = (HttpURLConnection) stsUrl.openConnection();
                    InputStream input = conn.getInputStream();
                    String jsonText = IOUtils.readStreamAsString(input, OSSConstants.DEFAULT_CHARSET_NAME);
                    JSONObject jsonObjs = new JSONObject(jsonText);
                    String ak = jsonObjs.getString("AccessKeyId");
                    String sk = jsonObjs.getString("AccessKeySecret");
                    String token = jsonObjs.getString("SecurityToken");
                    String expiration = jsonObjs.getString("Expiration");
                    return new OSSFederationToken(ak, sk, token, expiration);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        };

/*
        OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);

        // 构造下载文件请求。
// 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
        System.out.println("filePath："+filePath);
        System.out.println("name："+name);
        get = new GetObjectRequest(bucketName, filePath);
        oss = new OSSClient(this, endpoint, credentialProvider);
*/
    }

//    用户登录名称 ramtest@1678873764269912.onaliyun.com
//    AccessKey ID LTAI5tE6o24DpCszBqXB7vV1
//    AccessKey Secret zQLJOi1YrEXtrH36RTSFmQznzOXGIi
//    acs:ram::1678873764269912:role/ramonetest

    public void demo(){
        System.out.println("进入demo方法");
        oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
            @Override
            public void onSuccess(GetObjectRequest request, GetObjectResult result) {
// 开始读取数据。
                System.out.println("成功进入onSuccess");
                long length = result.getContentLength();
                if (length > 0) {
                    byte[] buffer = new byte[(int) length];
                    int readCount = 0;
                    while (readCount < length) {
                        try{
                            readCount += result.getObjectContent().read(buffer, readCount, (int) length - readCount);
                        }catch (Exception e){
                            OSSLog.logInfo(e.toString());
                        }
                    }
                    // 将下载后的文件存放在指定的本地路径，例如D:\\localpath\\exampleobject.jpg。
                    try {
                        FileOutputStream fout = new FileOutputStream(".\\app\\src\\main\\assets\\"+name);
                        fout.write(buffer);
                        fout.close();
                        System.out.println("到达load处");
                        pdfView.fromAsset(name).load();
                    } catch (Exception e) {
                        System.out.println("下载失败");
                        OSSLog.logInfo(e.toString());
                    }
                }
            }

            @Override
            public void onFailure(GetObjectRequest request, ClientException clientException,
                                  ServiceException serviceException)  {
                System.out.println("进入onFailure方法中");
            }
        });

    }


    public void sts() throws ExecutionException, InterruptedException {
        // HttpClient Configuration
        /*HttpClient httpClient = new ApacheAsyncHttpClientBuilder()
                .connectionTimeout(Duration.ofSeconds(10)) // Set the connection timeout time, the default is 10 seconds
                .responseTimeout(Duration.ofSeconds(10)) // Set the response timeout time, the default is 20 seconds
                .maxConnections(128) // Set the connection pool size
                .maxIdleTimeOut(Duration.ofSeconds(50)) // Set the connection pool timeout, the default is 30 seconds
                // Configure the proxy
                .proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("<your-proxy-hostname>", 9001))
                        .setCredentials("<your-proxy-username>", "<your-proxy-password>"))
                // If it is an https connection, you need to configure the certificate, or ignore the certificate(.ignoreSSL(true))
                .x509TrustManagers(new X509TrustManager[]{})
                .keyManagers(new KeyManager[]{})
                .ignoreSSL(false)
                .build();*/

//        // Configure Credentials authentication information, including ak, secret, token
//        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
//                .accessKeyId("<your-accessKeyId>")
//                .accessKeySecret("<your-accessKeySecret>")
//                //.securityToken("<your-token>") // use STS token
//                .build());
//
//        // Configure the Client
//        AsyncClient client = AsyncClient.builder()
//                .region("undefined") // Region ID
//                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
//                .credentialsProvider(provider)
//                //.serviceConfiguration(Configuration.create()) // Service-level configuration
//                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
//                .overrideConfiguration(
//                        ClientOverrideConfiguration.create()
//                                .setEndpointOverride("sts.cn-hangzhou.aliyuncs.com")
//                        //.setConnectTimeout(Duration.ofSeconds(30))
//                )
//                .build();
//
//        // Parameter settings for API request
//        AssumeRoleRequest assumeRoleRequest = AssumeRoleRequest.builder()
//                .durationSeconds(1L)
//                .policy("your_value")
//                .roleArn("your_value")
//                .roleSessionName("your_value")
//                // Request-level configuration rewrite, can set Http request parameters, etc.
//                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
//                .build();
//
//        // Asynchronously get the return value of the API request
//        CompletableFuture<AssumeRoleResponse> response = client.assumeRole(assumeRoleRequest);
//        // Synchronously get the return value of the API request
//        AssumeRoleResponse resp = response.get();
//        System.out.println(new Gson().toJson(resp));
//        // Asynchronous processing of return values
//        /*response.thenAccept(resp -> {
//            System.out.println(new Gson().toJson(resp));
//        }).exceptionally(throwable -> { // Handling exceptions
//            System.out.println(throwable.getMessage());
//            return null;
//        });*/
//
//        // Finally, close the client
//        client.close();
    }





}